#include "MainOperationWidget.h"
#include "ProcessWidget.h"
#include "GridTableWidget.h"
#include "SteelClientAPI.h"

// 前向声明，用于访问notifyDebugButtonCallbacks函数
// 该函数在SteelClientAPI.cpp中定义
extern void notifyDebugButtonCallbacks(int buttonType, bool isPressed);
#include <QApplication>
#include <QPainter>
#include <QDebug>
#include <QPixmap>
#include <QFont>
#include <QSignalBlocker>
#include <QByteArray>
#include <algorithm>
#include <cstring>

namespace {

NavTreeIndex mainIndexForStove(int stoveIndex)
{
    switch (stoveIndex) {
    case 0: return NavTreeIndex::Main_1;
    case 1: return NavTreeIndex::Main_2;
    case 2: return NavTreeIndex::Main_3;
    case 3: return NavTreeIndex::Main_4;
    case 4: return NavTreeIndex::Main_5;
    case 5: return NavTreeIndex::Main_6;
    default: return NavTreeIndex::Main_1;
    }
}

void fillKVItem(MainPageKVItem &item, const QString &name, const QString &value)
{
    QByteArray nameBytes = name.toUtf8();
    QByteArray valueBytes = value.toUtf8();
    std::strncpy(item.name, nameBytes.constData(), sizeof(item.name) - 1);
    item.name[sizeof(item.name) - 1] = '\0';
    std::strncpy(item.value, valueBytes.constData(), sizeof(item.value) - 1);
    item.value[sizeof(item.value) - 1] = '\0';
}

} // namespace

MainOperationWidget::MainOperationWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_currentStoveIndex(0)
    , m_currentNavIndex(NavTreeIndex::Main_1)
    , m_workingConditionCallbackId(-1)
    , m_materialCallbackId(-1)
    , m_oxygenLanceCallbackId(-1)
    , m_blowingCallbackId(-1)
    , m_chartCallbackId(-1)
    , m_operStageCallbackId(-1)
    , m_operTotalCallbackId(-1)
    , m_processCallbackId(-1)
    , m_videoCallbackId(-1)
    , m_updatingWorkingCondition(false)
    , m_updatingMaterial(false)
    , m_updatingOxygen(false)
    , m_updatingBlowing(false)
    , m_updatingOperStage(false)
    , m_updatingOperTotal(false)
    , m_updatingProcess(false)
    , m_updatingVideo(false)
{
    setupUI();
    setupConnections();
    registerCallbacks();
    setCurrentStoveIndex(0);
}

MainOperationWidget::~MainOperationWidget()
{
    unregisterCallbacks();
}

void MainOperationWidget::setupUI()
{
    // 主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(8);

    QWidget *topWidget = new QWidget();
    QHBoxLayout *topLayout = new QHBoxLayout(topWidget);
    topLayout->setContentsMargins(0, 0, 0, 0);
    topLayout->setSpacing(12);
    m_classInfoLabel = new QLabel();
    m_classInfoLabel->setText("班别信息：1234");
    m_classInfoLabel->setStyleSheet("border-image: url(:/img/images/Search bar.png); color: #ffffff; font-size: 16px; font-weight: medium; padding-left: 12px; padding-right: 12px;");
    m_classInfoLabel->setAlignment(Qt::AlignCenter);
    m_processWt = new ProcessWidget();
    topLayout->addWidget(m_classInfoLabel);
    topLayout->addWidget(m_processWt);
    m_mainLayout->addWidget(topWidget, 1);

    QHBoxLayout *middleLayout = new QHBoxLayout();
    QVBoxLayout *middleLeftLayout = new QVBoxLayout();
    m_workingConditionWt = new GridTableWidget("工况");
    m_materialWt = new GridTableWidget("料仓");
    setupWorkingConditionData();
    setupMaterialData();
    middleLeftLayout->addWidget(m_workingConditionWt);
    middleLeftLayout->addWidget(m_materialWt);
    middleLayout->addLayout(middleLeftLayout, 3);
    m_videoWt = new VideoWidget("视频监控");
    middleLayout->addWidget(m_videoWt, 6);
    m_blowingWt = new BlowingWidget("吹炼及提示");
    middleLayout->addWidget(m_blowingWt, 1);
    m_mainLayout->addLayout(middleLayout, 9);

    QHBoxLayout *bottomLayout = new QHBoxLayout();
    m_oxygenLanceWt = new OxygenLanceWidget("氧枪及转炉");
    bottomLayout->addWidget(m_oxygenLanceWt, 1);
    m_chartWt = new ChartWidget();
    bottomLayout->addWidget(m_chartWt, 3);
    m_operProcessWt = new OperProcessWidget();
    bottomLayout->addWidget(m_operProcessWt, 5);
    m_debugWt = new DebugWidget();
    bottomLayout->addWidget(m_debugWt, 1);
    m_mainLayout->addLayout(bottomLayout, 6);
}

void MainOperationWidget::setupConnections()
{
    if (m_workingConditionWt) {
        connect(m_workingConditionWt, &GridTableWidget::gridTableValueChanged,
                this, &MainOperationWidget::handleWorkingConditionValueChanged);
    }
    if (m_materialWt) {
        connect(m_materialWt, &GridTableWidget::gridTableValueChanged,
                this, &MainOperationWidget::handleMaterialValueChanged);
    }
    if (m_oxygenLanceWt) {
        connect(m_oxygenLanceWt, &OxygenLanceWidget::parameterValueChanged,
                this, &MainOperationWidget::handleOxygenLanceValueChanged);
    }
    if (m_debugWt) {
        connect(m_debugWt, &DebugWidget::buttonClicked,
                this, &MainOperationWidget::handleDebugButtonClicked);
    }
}

void MainOperationWidget::setupWorkingConditionData()
{
    if (!m_workingConditionWt) return;
    
    // 添加工况相关数据
    for (int i = 0; i < MAIN_PAGE_WORKING_MAX_ITEMS; ++i) { 
        m_workingConditionWt->addGridTableItem("");
    }
}

void MainOperationWidget::setupMaterialData()
{
    if (!m_materialWt) return;
    
    // 添加料仓数据，根据图片描述
    for (int i = 0; i < MAIN_PAGE_MATERIAL_MAX_ITEMS; ++i) {
        m_materialWt->addGridTableItem("");
    }
}

void MainOperationWidget::registerCallbacks()
{
    if (m_workingConditionCallbackId < 0) {
        m_workingConditionCallbackId = registerMainPageWorkingConditionCallback(&MainOperationWidget::workingConditionCallback, this);
        if (m_workingConditionCallbackId < 0) {
            qWarning() << "registerMainPageWorkingConditionCallback failed";
        }
    }
    if (m_materialCallbackId < 0) {
        m_materialCallbackId = registerMainPageMaterialCallback(&MainOperationWidget::materialCallback, this);
        if (m_materialCallbackId < 0) {
            qWarning() << "registerMainPageMaterialCallback failed";
        }
    }
    if (m_oxygenLanceCallbackId < 0) {
        m_oxygenLanceCallbackId = registerMainPageOxygenLanceCallback(&MainOperationWidget::oxygenLanceCallback, this);
        if (m_oxygenLanceCallbackId < 0) {
            qWarning() << "registerMainPageOxygenLanceCallback failed";
        }
    }
    if (m_chartCallbackId < 0) {
        m_chartCallbackId = registerMainPageChartCallback(&MainOperationWidget::chartCallback, this);
        if (m_chartCallbackId < 0) {
            qWarning() << "registerMainPageChartCallback failed";
        }
    }
    if (m_operStageCallbackId < 0) {
        m_operStageCallbackId = registerMainPageOperStageCallback(&MainOperationWidget::operStageCallback, this);
        if (m_operStageCallbackId < 0) {
            qWarning() << "registerMainPageOperStageCallback failed";
        }
    }
    if (m_operTotalCallbackId < 0) {
        m_operTotalCallbackId = registerMainPageOperTotalCallback(&MainOperationWidget::operTotalCallback, this);
        if (m_operTotalCallbackId < 0) {
            qWarning() << "registerMainPageOperTotalCallback failed";
        }
    }
    if (m_processCallbackId < 0) {
        m_processCallbackId = registerMainPageProcessCallback(&MainOperationWidget::processCallback, this);
        if (m_processCallbackId < 0) {
            qWarning() << "registerMainPageProcessCallback failed";
        }
    }
    if (m_videoCallbackId < 0) {
        m_videoCallbackId = registerMainPageVideoCallback(&MainOperationWidget::videoCallback, this);
        if (m_videoCallbackId < 0) {
            qWarning() << "registerMainPageVideoCallback failed";
        }
    }
}

void MainOperationWidget::unregisterCallbacks()
{
    if (m_workingConditionCallbackId > 0) {
        unregisterCallback(m_workingConditionCallbackId);
        m_workingConditionCallbackId = -1;
    }
    if (m_materialCallbackId > 0) {
        unregisterCallback(m_materialCallbackId);
        m_materialCallbackId = -1;
    }
    if (m_oxygenLanceCallbackId > 0) {
        unregisterCallback(m_oxygenLanceCallbackId);
        m_oxygenLanceCallbackId = -1;
    }
    if (m_chartCallbackId > 0) {
        unregisterCallback(m_chartCallbackId);
        m_chartCallbackId = -1;
    }
    if (m_operStageCallbackId > 0) {
        unregisterCallback(m_operStageCallbackId);
        m_operStageCallbackId = -1;
    }
    if (m_operTotalCallbackId > 0) {
        unregisterCallback(m_operTotalCallbackId);
        m_operTotalCallbackId = -1;
    }
    if (m_processCallbackId > 0) {
        unregisterCallback(m_processCallbackId);
        m_processCallbackId = -1;
    }
    if (m_videoCallbackId > 0) {
        unregisterCallback(m_videoCallbackId);
        m_videoCallbackId = -1;
    }
}

void MainOperationWidget::setCurrentStoveIndex(int stoveIndex)
{
    m_currentStoveIndex = stoveIndex;
    m_currentNavIndex = mainIndexForStove(stoveIndex);

    MainPageWorkingConditionData workingData{};
    if (SteelClientData::getMainPageWorkingConditionData(m_currentNavIndex, workingData)) {
        applyWorkingConditionData(workingData);
    } else {
        MainPageWorkingConditionData empty{};
        applyWorkingConditionData(empty);
    }

    MainPageMaterialData materialData{};
    if (SteelClientData::getMainPageMaterialData(m_currentNavIndex, materialData)) {
        applyMaterialData(materialData);
    } else {
        MainPageMaterialData empty{};
        applyMaterialData(empty);
    }

    MainPageOxygenLanceData oxygenData{};
    if (SteelClientData::getMainPageOxygenLanceData(m_currentNavIndex, oxygenData)) {
        applyOxygenLanceData(oxygenData);
    } else {
        MainPageOxygenLanceData empty{};
        applyOxygenLanceData(empty);
    }

    MainPageBlowingData blowingData{};
    if (SteelClientData::getMainPageBlowingData(m_currentNavIndex, blowingData)) {
        applyBlowingData(blowingData);
    } else {
        MainPageBlowingData empty{};
        applyBlowingData(empty);
    }

    MainPageChartData chartData{};
    if (SteelClientData::getMainPageChartData(m_currentNavIndex, chartData)) {
        applyChartData(chartData);
    } else {
        MainPageChartData empty{};
        applyChartData(empty);
    }

    MainPageOperStageData stageData{};
    if (SteelClientData::getMainPageOperStageData(m_currentNavIndex, stageData)) {
        applyOperStageData(stageData);
    } else {
        MainPageOperStageData emptyStage{};
        applyOperStageData(emptyStage);
    }

    MainPageOperTotalData totalData{};
    if (SteelClientData::getMainPageOperTotalData(m_currentNavIndex, totalData)) {
        applyOperTotalData(totalData);
    } else {
        MainPageOperTotalData emptyTotal{};
        applyOperTotalData(emptyTotal);
    }

    MainPageProcessData processData{};
    if (SteelClientData::getMainPageProcessData(m_currentNavIndex, processData)) {
        applyProcessData(processData);
    } else {
        MainPageProcessData emptyProcess{};
        applyProcessData(emptyProcess);
    }

    MainPageVideoData videoData{};
    if (SteelClientData::getMainPageVideoData(m_currentNavIndex, videoData)) {
        applyVideoData(videoData);
    } else {
        MainPageVideoData emptyVideo{};
        applyVideoData(emptyVideo);
    }

    // 应用当前炉子的按钮显示模式设置
    if (m_videoWt) {
        int buttonMode;
        if (SteelClientData::getVideoButtonDisplayMode(m_currentNavIndex, buttonMode)) {
            VideoWidget::ButtonDisplayMode displayMode;
            switch (buttonMode) {
                case 0:
                    displayMode = VideoWidget::ShowBothButtons;
                    break;
                case 1:
                    displayMode = VideoWidget::ShowNormalButtonOnly;
                    break;
                case 2:
                    displayMode = VideoWidget::ShowAbnormalButtonOnly;
                    break;
                default:
                    displayMode = VideoWidget::ShowBothButtons;
                    break;
            }
            m_videoWt->setButtonDisplayMode(displayMode);
        }
    }
}

void MainOperationWidget::setWorkingConditionData(const QVector<TableItemData> &items)
{
    MainPageWorkingConditionData data{};
    data.count = std::min<int>(items.size(), MAIN_PAGE_WORKING_MAX_ITEMS);
    for (int i = 0; i < data.count; ++i) {
        fillKVItem(data.items[i], items[i].name, items[i].value);
    }
    SteelClientData::setMainPageWorkingConditionData(m_currentNavIndex, data);
}

void MainOperationWidget::setMaterialData(const QVector<TableItemData> &items)
{
    MainPageMaterialData data{};
    data.count = std::min<int>(items.size(), MAIN_PAGE_MATERIAL_MAX_ITEMS);
    for (int i = 0; i < data.count; ++i) {
        fillKVItem(data.items[i], items[i].name, items[i].value);
    }
    SteelClientData::setMainPageMaterialData(m_currentNavIndex, data);
}

void MainOperationWidget::setOxygenLanceData(const MainPageOxygenLanceData &data)
{
    SteelClientData::setMainPageOxygenLanceData(m_currentNavIndex, data);
}

void MainOperationWidget::setBlowingData(const MainPageBlowingData &data)
{
    SteelClientData::setMainPageBlowingData(m_currentNavIndex, data);
}

void MainOperationWidget::setChartData(const MainPageChartData &data)
{
    SteelClientData::setMainPageChartData(m_currentNavIndex, data);
}

void MainOperationWidget::setProcessData(const MainPageProcessData &data)
{
    SteelClientData::setMainPageProcessData(m_currentNavIndex, data);
}

void MainOperationWidget::setVideoData(const MainPageVideoData &data)
{
    SteelClientData::setMainPageVideoData(m_currentNavIndex, data);
}

WId MainOperationWidget::videoWindowHandle() const
{
    if (m_videoWt) {
        return m_videoWt->getVideoWindowHandle();
    }
    return 0;
}

VideoWidget* MainOperationWidget::getVideoWidget() const
{
    return m_videoWt;
}

NavTreeIndex MainOperationWidget::getCurrentNavIndex() const
{
    return m_currentNavIndex;
}

void MainOperationWidget::setChartTableItem(int row, int column, const QString& value)
{
    if (m_chartWt) {
        m_chartWt->setTableItem(row, column, value);
    }
    QByteArray valueBytes = value.toUtf8();
    SteelClientData::setMainPageChartTableItem(m_currentNavIndex, row, column, valueBytes.constData());
}

QString MainOperationWidget::chartTableItem(int row, int column) const
{
    if (m_chartWt) {
        return m_chartWt->tableItem(row, column);
    }
    return QString();
}

void MainOperationWidget::setOperStageData(const MainPageOperStageData &data)
{
    SteelClientData::setMainPageOperStageData(m_currentNavIndex, data);
}

void MainOperationWidget::setOperStageItem(int row, int column, const QString& value)
{
    if (m_operProcessWt) {
        m_operProcessWt->setStageItem(row, column, value);
    }
    if (!m_updatingOperStage) {
        QByteArray valueBytes = value.toUtf8();
        SteelClientData::setMainPageOperStageItem(m_currentNavIndex, row, column, valueBytes.constData());
    }
}

QString MainOperationWidget::operStageItem(int row, int column) const
{
    if (m_operProcessWt) {
        return m_operProcessWt->stageItem(row, column);
    }
    return QString();
}

void MainOperationWidget::setOperTotalData(const MainPageOperTotalData &data)
{
    SteelClientData::setMainPageOperTotalData(m_currentNavIndex, data);
}

void MainOperationWidget::setOperTotalItem(int row, int column, const QString& value)
{
    if (m_operProcessWt) {
        m_operProcessWt->setTotalItem(row, column, value);
    }
    if (!m_updatingOperTotal) {
        QByteArray valueBytes = value.toUtf8();
        SteelClientData::setMainPageOperTotalItem(m_currentNavIndex, row, column, valueBytes.constData());
    }
}

QString MainOperationWidget::operTotalItem(int row, int column) const
{
    if (m_operProcessWt) {
        return m_operProcessWt->totalItem(row, column);
    }
    return QString();
}

void MainOperationWidget::applyWorkingConditionData(const MainPageWorkingConditionData &data)
{
    if (!m_workingConditionWt) return;
    m_updatingWorkingCondition = true;
    QVector<GridTableWidget::GridTableItem> items = m_workingConditionWt->getAllGridTableItems();
    int limit = items.size();
    for (int i = 0; i < limit; ++i) {
        QString value;
        QString name;
        if (i < data.count) {
            name = QString::fromUtf8(data.items[i].name);
            value = QString::fromUtf8(data.items[i].value);
        }
        if (!name.isEmpty()) {
            m_workingConditionWt->setGridTableName(i, name);
        }
        m_workingConditionWt->setGridTableValue(i, value);
    }
    m_updatingWorkingCondition = false;
}

void MainOperationWidget::applyMaterialData(const MainPageMaterialData &data)
{
    if (!m_materialWt) return;
    m_updatingMaterial = true;
    QVector<GridTableWidget::GridTableItem> items = m_materialWt->getAllGridTableItems();
    int limit = items.size();
    for (int i = 0; i < limit; ++i) {
        QString value;
        QString name;
        if (i < data.count) {
            name = QString::fromUtf8(data.items[i].name);
            value = QString::fromUtf8(data.items[i].value);
        }
        if (!name.isEmpty()) {
            m_materialWt->setGridTableName(i, name);
        }
        m_materialWt->setGridTableValue(i, value);
    }
    m_updatingMaterial = false;
}

void MainOperationWidget::applyOxygenLanceData(const MainPageOxygenLanceData &data)
{
    if (!m_oxygenLanceWt) return;
    m_updatingOxygen = true;

    auto formatValue = [](double value) {
        return QString::number(value, 'f', 2);
    };

    m_oxygenLanceWt->setParameterValue(QStringLiteral("氧气流量"), formatValue(data.oxygenFlow));
    m_oxygenLanceWt->setParameterValue(QStringLiteral("氧枪高度"), formatValue(data.lanceHeight));
    m_oxygenLanceWt->setParameterValue(QStringLiteral("读数吹氧量"), formatValue(data.readingBlowQuantity));
    m_oxygenLanceWt->setParameterValue(QStringLiteral("累计吹氧量"), formatValue(data.accumulatedBlowQuantity));
    m_oxygenLanceWt->setParameterValue(QStringLiteral("转炉角度"), formatValue(data.converterAngle));
    m_oxygenLanceWt->setParameterValue(QStringLiteral("氧气压力"), formatValue(data.oxygenPressure));

    m_updatingOxygen = false;
}

void MainOperationWidget::applyBlowingData(const MainPageBlowingData &data)
{
    if (!m_blowingWt) return;
    m_updatingBlowing = true;

    auto toString = [](const char *text) -> QString {
        return QString::fromUtf8(text);
    };

    m_blowingWt->setCurrentBlowingTime(toString(data.currentBlowingTime));
    m_blowingWt->setEstimatedRemainingTime(toString(data.estimatedRemainingTime));
    m_blowingWt->setCurrentTemperature(toString(data.currentTemperature));
    m_blowingWt->setCurrentCarbonContent(toString(data.currentCarbonContent));
    m_blowingWt->setOperatingMode(toString(data.operatingMode));

    m_updatingBlowing = false;
}

void MainOperationWidget::applyChartData(const MainPageChartData &data)
{
    if (!m_chartWt) {
        return;
    }

    auto convertSeries = [](const MainPageChartSeriesData &series) {
        QList<QPointF> points;
        int count = series.count;
        if (count < 0) {
            count = 0;
        } else if (count > MAIN_PAGE_CHART_MAX_POINTS) {
            count = MAIN_PAGE_CHART_MAX_POINTS;
        }
        points.reserve(count);
        for (int i = 0; i < count; ++i) {
            points.append(QPointF(series.points[i].x, series.points[i].y));
        }
        return points;
    };

    // 临时禁用自动范围调整，避免每次设置数据系列时都更新范围
    bool autoRangeWasEnabled = m_chartWt->isAutoRangeEnabled();
    m_chartWt->setAutoRangeEnabled(false);
    
    m_chartWt->setDataSeries(ChartWidget::ActualLancePos, convertSeries(data.actualLanceSeries));
    m_chartWt->setDataSeries(ChartWidget::StandardLancePos, convertSeries(data.standardLanceSeries));
    m_chartWt->setDataSeries(ChartWidget::OxygenFlow, convertSeries(data.oxygenFlowSeries));
    m_chartWt->setDataSeries(ChartWidget::LimeClass, convertSeries(data.limeClassSeries));
    m_chartWt->setDataSeries(ChartWidget::RawWhiteClass, convertSeries(data.rawWhiteClassSeries));
    m_chartWt->setDataSeries(ChartWidget::IronOreClass, convertSeries(data.ironOreClassSeries));

    // 设置完所有数据后，根据数据更新坐标范围
    m_chartWt->updateRangeFromData();
    
    // 恢复之前的自动范围调整状态
    m_chartWt->setAutoRangeEnabled(autoRangeWasEnabled);

    for (int row = 0; row < MAIN_PAGE_CHART_TABLE_ROWS; ++row) {
        for (int col = 0; col < MAIN_PAGE_CHART_TABLE_COLUMNS; ++col) {
            const char* text = data.tableData.items[row][col];
            if (text && text[0] != '\0') {
                m_chartWt->setTableItem(row, col, QString::fromUtf8(text));
            } else {
                m_chartWt->setTableItem(row, col, QString());
            }
        }
    }
}

void MainOperationWidget::applyOperStageData(const MainPageOperStageData &data)
{
    if (!m_operProcessWt) {
        return;
    }
    m_updatingOperStage = true;
    for (int row = 0; row < MAIN_PAGE_OPER_STAGE_ROWS; ++row) {
        for (int col = 0; col < MAIN_PAGE_OPER_STAGE_COLUMNS; ++col) {
            const char* text = data.stageItems[row][col];
            if (text && text[0] != '\0') {
                m_operProcessWt->setStageItem(row, col, QString::fromUtf8(text));
            } else {
                m_operProcessWt->setStageItem(row, col, QString());
            }
        }
    }
    m_updatingOperStage = false;
}

void MainOperationWidget::applyOperTotalData(const MainPageOperTotalData &data)
{
    if (!m_operProcessWt) {
        return;
    }
    m_updatingOperTotal = true;
    for (int row = 0; row < MAIN_PAGE_OPER_TOTAL_ROWS; ++row) {
        for (int col = 0; col < MAIN_PAGE_OPER_TOTAL_COLUMNS; ++col) {
            const char* text = data.totalItems[row][col];
            if (text && text[0] != '\0') {
                m_operProcessWt->setTotalItem(row, col, QString::fromUtf8(text));
            } else {
                m_operProcessWt->setTotalItem(row, col, QString());
            }
        }
    }
    m_updatingOperTotal = false;
}

void MainOperationWidget::applyProcessData(const MainPageProcessData &data)
{
    if (!m_processWt) {
        return;
    }
    m_updatingProcess = true;

    int clampedStage = std::clamp(data.currentStage, 0, MAIN_PAGE_PROCESS_STAGE_COUNT - 1);
    m_processWt->setCurrentStage(static_cast<ProcessWidget::ProcessStage>(clampedStage));

    QString timeText = QString::fromUtf8(data.currentTime);
    if (!timeText.isEmpty()) {
        m_processWt->setCurrentTime(timeText);
    } else {
        m_processWt->setCurrentTime(QString());
    }

    for (int i = 0; i < MAIN_PAGE_PROCESS_STAGE_COUNT; ++i) {
        bool completed = data.stageCompleted[i];
        m_processWt->setStageCompleted(static_cast<ProcessWidget::ProcessStage>(i), completed);
    }

    m_updatingProcess = false;
}

void MainOperationWidget::applyVideoData(const MainPageVideoData &data)
{
    if (!m_videoWt) {
        return;
    }
    m_updatingVideo = true;

    m_videoWt->setCurrentStatus(QString::fromUtf8(data.status));
    m_videoWt->setOperationSuggestion(QString::fromUtf8(data.suggestion));
    m_videoWt->setAbnormal(data.abnormal);

    m_updatingVideo = false;
}

void MainOperationWidget::handleWorkingConditionValueChanged(int index, const QString &value)
{
    if (m_updatingWorkingCondition) {
        return;
    }
    QVector<GridTableWidget::GridTableItem> items = m_workingConditionWt->getAllGridTableItems();
    MainPageWorkingConditionData data{};
    data.count = std::min<int>(items.size(), MAIN_PAGE_WORKING_MAX_ITEMS);
    for (int i = 0; i < data.count; ++i) {
        fillKVItem(data.items[i], items[i].name, items[i].value);
    }
    SteelClientData::setMainPageWorkingConditionData(m_currentNavIndex, data);
    if (index >= 0 && index < items.size()) {
        emit workingConditionItemChanged(index, items[index].name, value);
    }
}

void MainOperationWidget::handleMaterialValueChanged(int index, const QString &value)
{
    if (m_updatingMaterial) {
        return;
    }
    QVector<GridTableWidget::GridTableItem> items = m_materialWt->getAllGridTableItems();
    MainPageMaterialData data{};
    data.count = std::min<int>(items.size(), MAIN_PAGE_MATERIAL_MAX_ITEMS);
    for (int i = 0; i < data.count; ++i) {
        fillKVItem(data.items[i], items[i].name, items[i].value);
    }
    SteelClientData::setMainPageMaterialData(m_currentNavIndex, data);
    if (index >= 0 && index < items.size()) {
        emit materialItemChanged(index, items[index].name, value);
    }
}

void MainOperationWidget::handleDebugButtonClicked(DebugWidget::DebugButtonType buttonType, bool isPressed)
{
    // 将DebugWidget的按钮类型转换为API的按钮类型（int）
    int apiButtonType = static_cast<int>(buttonType);
    // 通知所有注册的回调函数
    notifyDebugButtonCallbacks(apiButtonType, isPressed);
}

void MainOperationWidget::handleOxygenLanceValueChanged(const QString &name, const QString &value)
{
    if (m_updatingOxygen) {
        return;
    }

    MainPageOxygenLanceData data{};
    SteelClientData::getMainPageOxygenLanceData(m_currentNavIndex, data);

    auto parseValue = [&](double current) {
        bool ok = false;
        double converted = value.trimmed().toDouble(&ok);
        return ok ? converted : current;
    };

    if (name == QStringLiteral("氧气流量")) {
        data.oxygenFlow = parseValue(data.oxygenFlow);
    } else if (name == QStringLiteral("氧枪高度")) {
        data.lanceHeight = parseValue(data.lanceHeight);
    } else if (name == QStringLiteral("读数吹氧量")) {
        data.readingBlowQuantity = parseValue(data.readingBlowQuantity);
    } else if (name == QStringLiteral("累计吹氧量")) {
        data.accumulatedBlowQuantity = parseValue(data.accumulatedBlowQuantity);
    } else if (name == QStringLiteral("转炉角度")) {
        data.converterAngle = parseValue(data.converterAngle);
    } else if (name == QStringLiteral("氧气压力")) {
        data.oxygenPressure = parseValue(data.oxygenPressure);
    }

    SteelClientData::setMainPageOxygenLanceData(m_currentNavIndex, data);
    emit oxygenLanceDataChanged(data);
}

void MainOperationWidget::handleWorkingConditionDataUpdate(NavTreeIndex index, const MainPageWorkingConditionData &data)
{
    if (index == m_currentNavIndex) {
        applyWorkingConditionData(data);
    }
}

void MainOperationWidget::handleMaterialDataUpdate(NavTreeIndex index, const MainPageMaterialData &data)
{
    if (index == m_currentNavIndex) {
        applyMaterialData(data);
    }
}

void MainOperationWidget::handleOxygenLanceDataUpdate(NavTreeIndex index, const MainPageOxygenLanceData &data)
{
    if (index == m_currentNavIndex) {
        applyOxygenLanceData(data);
        emit oxygenLanceDataChanged(data);
    }
}

void MainOperationWidget::handleBlowingDataUpdate(NavTreeIndex index, const MainPageBlowingData &data)
{
    if (index == m_currentNavIndex) {
        applyBlowingData(data);
        emit blowingDataChanged(data);
    }
}

void MainOperationWidget::handleChartDataUpdate(NavTreeIndex index, const MainPageChartData &data)
{
    if (index == m_currentNavIndex) {
        applyChartData(data);
    }
}

void MainOperationWidget::handleOperStageDataUpdate(NavTreeIndex index, const MainPageOperStageData &data)
{
    if (index == m_currentNavIndex) {
        applyOperStageData(data);
    }
}

void MainOperationWidget::handleOperTotalDataUpdate(NavTreeIndex index, const MainPageOperTotalData &data)
{
    if (index == m_currentNavIndex) {
        applyOperTotalData(data);
    }
}

void MainOperationWidget::handleProcessDataUpdate(NavTreeIndex index, const MainPageProcessData &data)
{
    if (index == m_currentNavIndex) {
        applyProcessData(data);
    }
}

void MainOperationWidget::handleVideoDataUpdate(NavTreeIndex index, const MainPageVideoData &data)
{
    if (index == m_currentNavIndex) {
        applyVideoData(data);
    }
}

void MainOperationWidget::workingConditionCallback(NavTreeIndex index, const MainPageWorkingConditionData* data, void* userData)
{
    if (!userData || !data) {
        return;
    }
    MainOperationWidget *widget = static_cast<MainOperationWidget*>(userData);
    widget->handleWorkingConditionDataUpdate(index, *data);
}

void MainOperationWidget::materialCallback(NavTreeIndex index, const MainPageMaterialData* data, void* userData)
{
    if (!userData || !data) {
        return;
    }
    MainOperationWidget *widget = static_cast<MainOperationWidget*>(userData);
    widget->handleMaterialDataUpdate(index, *data);
}

void MainOperationWidget::oxygenLanceCallback(NavTreeIndex index, const MainPageOxygenLanceData* data, void* userData)
{
    if (!userData || !data) {
        return;
    }
    MainOperationWidget *widget = static_cast<MainOperationWidget*>(userData);
    widget->handleOxygenLanceDataUpdate(index, *data);
}

void MainOperationWidget::blowingCallback(NavTreeIndex index, const MainPageBlowingData* data, void* userData)
{
    if (!userData || !data) {
        return;
    }
    MainOperationWidget *widget = static_cast<MainOperationWidget*>(userData);
    widget->handleBlowingDataUpdate(index, *data);
}

void MainOperationWidget::chartCallback(NavTreeIndex index, const MainPageChartData* data, void* userData)
{
    if (!userData || !data) {
        return;
    }
    MainOperationWidget *widget = static_cast<MainOperationWidget*>(userData);
    widget->handleChartDataUpdate(index, *data);
}

void MainOperationWidget::operStageCallback(NavTreeIndex index, const MainPageOperStageData* data, void* userData)
{
    if (!userData || !data) {
        return;
    }
    MainOperationWidget *widget = static_cast<MainOperationWidget*>(userData);
    widget->handleOperStageDataUpdate(index, *data);
}

void MainOperationWidget::operTotalCallback(NavTreeIndex index, const MainPageOperTotalData* data, void* userData)
{
    if (!userData || !data) {
        return;
    }
    MainOperationWidget *widget = static_cast<MainOperationWidget*>(userData);
    widget->handleOperTotalDataUpdate(index, *data);
}

void MainOperationWidget::processCallback(NavTreeIndex index, const MainPageProcessData* data, void* userData)
{
    if (!userData || !data) {
        return;
    }
    MainOperationWidget *widget = static_cast<MainOperationWidget*>(userData);
    widget->handleProcessDataUpdate(index, *data);
}

void MainOperationWidget::videoCallback(NavTreeIndex index, const MainPageVideoData* data, void* userData)
{
    if (!userData || !data) {
        return;
    }
    MainOperationWidget *widget = static_cast<MainOperationWidget*>(userData);
    widget->handleVideoDataUpdate(index, *data);
}
